package com.opdar.athena.client.agent.base;

import com.opdar.athena.client.agent.server.IoSession;
import com.opdar.athena.base.Message;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by shiju on 2017/6/29.
 */
public class InvokeHandler {
    private Map<String,Method> commandMethods = new HashMap<String, Method>();
    private String beanName;
    public void putCommand(String command,Method method) {
        commandMethods.put(command,method);
    }

    public String getBeanName() {
        return beanName;
    }

    public void setBeanName(String beanName) {
        this.beanName = beanName;
    }

    public <T extends Message> Object invoke(String command, Object object, T message, IoSession session) throws InvocationTargetException, IllegalAccessException {
        if(commandMethods.containsKey(command)){
            Method method = commandMethods.get(command);
            Object[] parameters = new Object[method.getParameterTypes().length];
            for(int i=0;i<method.getParameterTypes().length;i++){
                Class<?> clz = method.getParameterTypes()[i];
                if(Message.class.isAssignableFrom(clz)){
                    parameters[i] = message;
                }else if(IoSession.class.isAssignableFrom(clz)){
                    parameters[i] = session;
                }
            }
            return method.invoke(object,parameters);
        }
        return null;
    }
}
